//素金详情
var APP=is_app();
var ItemJson={};//货品详情
var supplierJson={};//供应商详情
var imgs;
var supplier;
var RATE=Number($.cookie("PrimeGoldRate"));//汇率
var app_url=location.origin;
var MANAGE_MODE=false;
var MOBILE=true;
var TEAM=0;
var PlaceOrder=false;//代下单
(function(){
	var productItem={
		init:function(){
			args = GetUrlParms();				
			if(args["ID"]!=undefined){						
				 PrimeGoldsID = args["ID"];//产品ID					 
			}
			if(args["team"]!=undefined){
				TEAM=args["team"];//2为现货
			}
			if(args["cid"]!=undefined){
				 Customer_id = args["cid"];	
				 PlaceOrder=true;//代下单
			} 
			this.bindEvent();
			this.loadEmeraldItem();
		},
		bindEvent:function(){
			var self=this;		
			//立即购买
			$("#edit_btn_box").on("click","#add_to_order",function(){
				var orderJson={};
            	orderJson.orderID = [];
            	orderJson.type="prime_golds";
	            orderJson.orderID.push(PrimeGoldsID);
	            if(PlaceOrder==true){
	            	var link_url="/Customer/SubmitDiaOrder?type=6&cid="+Customer_id;
	            }else{
	            	var link_url="/Customer/SubmitDiaOrder?type=6";
	            }	
	            if(APP){
	            	var appJson={};
	            	appJson.title="确认下单";
	            	appJson.url=app_url+link_url;
	            	appJson.content=JSON.stringify(orderJson);
	            	YiYi_APP.submitOrder(JSON.stringify(appJson))
	            }else{
	            	var action=link_url;
				  	form = $("<form method='post' id='params_form' action='"+action+"'>"+
				   	"<input type='text' value='"+JSON.stringify(orderJson)+"' name='params'></form>")
					$("#form_box").html(form);
					$("#params_form").submit();
	            }
			});
			//删除产品
			$("#edit_btn_box").on("click","#emerald_delete",function(){
				myApp.confirm('您确定要删除该货品吗？', function () {
			        self.DelPrimeGolds();
			   	});				
			});	
			
			//app点击证书
			$("#product_detail").on("click","#app_cert_link",function(){
				app_linkCert();
			});						
			//app编辑
			$("#edit_btn_box").on("click","#edit_btn",function(){
				var url=$(this).attr("data-href");
				//var title=$("#app_title").text();				
				if(APP){
					var editJson={};
					editJson.url=app_url+url;
					editJson.title="素金编辑";
					YiYi_APP.editGoods(JSON.stringify(editJson));
				}else{
					location.href =url;
				}
			});
			//加入购物车
			$("#edit_btn_box").on("click","#add_to_cart",function(){
				self.addCart();
			});
			//继续逛逛
            $(".page").on("click","#go_shop",function(){
            	var linkUrl="/Customer/PrimeGold?team=0";
            	if(APP){
	           		YiYi_APP.finish();
            	}else{
            		location.href=linkUrl;
            	}
            });
             //去购物车
            $(".page").on("click","#go_cart",function(){
            	var linkUrl="/Customer/PrimeGoldCart";
            	if(APP){
            		var appJson={};
	           		appJson.title="购物车";
	           		appJson.function_menu="shopping_cart";
	           		appJson.url=app_url+linkUrl;		           		
	           		YiYi_APP.showExistingPage(JSON.stringify(appJson));
            	}else{
            		location.href=linkUrl;
            	}
            });
			
		},
		//加入购物车
		addCart:function(){
			myApp.showPreloader('正在加入中，请稍等...');
			var submitJson={};
			submitJson.CustomerID=CustomerID;
			submitJson.CartType=1;
			submitJson.IDs=PrimeGoldsID;
			$.ajax({
				url:"/Team/AddPrimeGoldsCart",
				type:"POST",
				data:JSON.stringify(submitJson),
				contentType:"application/json;charset=utf8",
				success:function(result){
					var res=eval('('+result+')');
					myApp.hidePreloader();
					if(res.msgcode==true){
						var strTip = "";
						strTip = '<div class="tip-box order-tip">'+
							'<div class="tip-text">'+
							 	'<div class="tip-title">'+
							 		'<div class="">加入购物车成功</div>'+
							 	'</div>'+
							 	'<div class="buttons">'+
							 		'<span class="btn-left" id="go_shop"><a href="#">继续逛逛</a></span>'+
							 		'<span class="btn-right" id="go_cart"><a href="#">去购物车</a></span>'+
							 	'</div>'+
							'</div>'+
						'</div>';
					$("#app_no_header").after(strTip);
					$(".tip-box").show();
					//   @*主题色start*@
			        $(document.createElement("script")).attr("src","/Js/ThemesColor.js").appendTo("html");
					//  @*主题色end*@
					}else{
						myApp.alert(res.msginfo);
					}
				}
			});
		},
		//加载详情
		loadEmeraldItem:function(){
		    myApp.showIndicator();//显示加载中
			var self=this;
			var submitJson={};
			submitJson.ID=PrimeGoldsID;
			if(TEAM==0){
				submitJson.CustomerID = customerId;//客户ID
			}
			if(TEAM==2){
				submitJson.IsMyStock=true;
			}
			$.ajax({
				url:'/Team/GetPrimeGold',
				type:'POST',
				data: JSON.stringify(submitJson),
				dataType:'JSON',
				contentType: "application/json; charset=utf8",
				success:function(result){
					var res=eval('(' + result + ')');
					ItemJson=res;
					if (res.msgcode == true) {
						var data=res.msginfo;
						//self.LoadSupplierDetail(data.Supplier);
						imgs = data.Images.split("|");
						var lis="";
						var app_lis=[];
						var span_lis="";
						imgArray=[];
				        for (var i=0; i< imgs.length;i++) {
				            if (imgs[i].length > 10) {
				                var span_li='<span data-val="'+i+'"></span>';
				                span_lis+=span_li;
				                var li = '<li><a href="'+imgs[i] +'"><img src="' + imgs[i] + '" class="image' + i + '"/></a></li>';
				                lis += li;
				                //app_li='<li data-turn="'+i+'"><a href="#"><img _src="' + imgs[i] + '" src="' + imgs[i] + '" /></a></li>';
				        		//app_lis+=app_li;
				        		var big = imgs[i].replace('800x800', '1920x1920');
				        		imgArray.push(big)
				        		var app_li={url: imgs[i], caption: i};
				        		app_lis.push(app_li);
				            }else{
				            	var img_null='/images/no_img.jpg';
				            	var lis='<li><a href="/images/no_img.jpg"><img src="'+img_null+'" class="image' + i + '"/></a></li>';
				            	var app_li={url: img_null, caption: i};
				        		app_lis.push(app_li);
				            	imgArray.push(img_null)
				            }
				        }
						
				        //图片列
				        $("#img_box").html(lis);
						$("#Indicators").html(span_lis);
						if(MOBILE){
							(function(window, Util, PhotoSwipe){
								document.addEventListener('DOMContentLoaded', function(){
									var options = {},
										instance = PhotoSwipe.attach( window.document.querySelectorAll('.ps-carousel-item img'), options );								
								}, false);
								Util.Events.domReady(function(e){									
									var instance, indicators;									
									instance = PhotoSwipe.attach(	
											app_lis,
										{
											target: window.document.querySelectorAll('#PhotoSwipeTarget')[0],
											preventHide: true,
											getImageSource: function(obj){
													return obj.url;
											},
											getImageCaption: function(obj){
												return obj.caption;
											}
										}
									);									
									indicators = window.document.querySelectorAll('#Indicators span');
									instance.addEventHandler(PhotoSwipe.EventTypes.onDisplayImage, function(e){										
										var i, len;
										for (i=0, len=indicators.length; i<len; i++){
											indicators[i].setAttribute('class', '');
										}
										indicators[e.index].setAttribute('class', 'current');										
									});									
									instance.show(0);									
								});								
							}(window, window.Code.Util, window.Code.PhotoSwipe))							
						}                       

						//详情参数
						var emeralds_detail=[
						'<div class="detail_left">',
							'<div class="tr">',
			   					'<div class="td td_str">类型：</div>', 
			   				 	'<div class="td td_data" id="app_title">素金</div>',
		 					'</div>', 
		 					'<div class="tr">',
			   				 	'<div class="td td_str">工艺造型：</div>', 
			   				 	'<div class="td td_data">',GetText("prime_golds",1,data.Style,"Style"),'</div>',
			 				'</div>',
			 				'<div class="tr">',
			    				'<div class="td td_str">系类名称：</div>', 
			   				 	'<div class="td td_data">',data.Series,'</div>', 
			   				'</div>',
			   				'<div class="tr">', 
			    				'<div class="td td_str">约重(克)：</div>',
			   				 	'<div class="td td_data">',GetText("prime_golds",1,data.Weight,"Weight"),'</div>', 
			   				'</div>',
			   				'<div class="tr">', 
			    				'<div class="td td_str">材&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;质：</div>', 
			   				 	'<div class="td td_data">',GetText("prime_golds",1,data.Material,"Material"),'</div>', 
			   				'</div>',
			 				
			 			'</div>',
			 			'<div class="detail_right">',
			 				'<div class="tr">',
			 				 	'<div class="td td_str">品&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;类：</div>',
			   				 	'<div class="td td_data">',GetText("prime_golds",1,data.Type,"Type"),'</div>',
			 				'</div>',
			 				'<div class="tr">',
			   				 	'<div class="td td_str">成品证书：</div>',
			   				 	'<div class="td td_data">',data.CertType,'</div>',
			 				'</div>',
			 				'<div class="tr">',
			 					'<div class="td td_str">数&nbsp;量&nbsp;(件)：</div>', 
			   					'<div class="td td_data">',data.StockNumber,'</div>',
			 				'</div>',
			 				'<div class="tr">',
			 				 	'<div class="td td_str">总&nbsp;重&nbsp;(克)：</div>', 
			   				 	'<div class="td td_data">',data.TotalWeight,'</div>', 
			 				'</div>',
			 				'<div class="tr">', 
			    				'<div class="td td_str">货&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号：</div>', 
			   				 	'<div class="td td_data">',data.OriginSN,'</div>', 
			   				'</div>',			   				
			 			'</div>',
		 				'<div class="tr tr_block">',
		 				 	'<div class="td td_str">所&nbsp;在&nbsp;地：</div>', 
		   				 	'<div class="td td_data">',data.Country,data.State,'</div>', 
		 				'</div>',
		 				'<div class="tr tr_block tr_normal">',
		 				 	'<div class="td td_str">备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注：</div>', 
		   				 	'<div class="td td_data">',data.Remark,'</div>', 
		 				'</div>',
		 				'<div class="tr tr_block tr_normal">',
		 				 	'<div class="td td_str">详&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;情：</div>', 
		   				 	'<div class="td td_data">',data.Details,'</div>', 
		 				'</div>',
		 				'<div class="tr tr_block  tr_normal">',
		 				 	'<div class="td td_str">上传时间：</div>', 
		   				 	'<div class="td td_data">', DateTimeFormat(data.InsertTime), '</div>',
			 			'</div>',
			 			'<div class="tr tr_block  tr_normal">',
		 				 	'<div class="td td_str">汇&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;率：</div>', 
		   				 	'<div class="td td_data">',RATE,'</div>', 
			 			'</div>',
			 			'<div class="detail_left">',
			 				'<div class="tr">',
			 					'<div class="td td_str">单价工费：</div>',
			 					'<div class="td td_data price_color">',formatRMBPrice(data.LaborFee),'</div>',
			 				'</div>',
			 			'</div>',
			 			'<div class="detail_right">',
			 				'<div class="tr">',
			 					'<div class="td td_str">金&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;价：</div>',
			 					'<div class="td td_data price_color">',formatRMBPrice(data.GoldPrice),'</div>',
			 				'</div>',			 				
			 			'</div>'					 				   				
			   				].join('');
						
						$("#product_detail").html(emeralds_detail);
						//管理页面有编辑和删除按钮
						var editHtmlStr= [        
							'<a href="#" style="margin-right:20px;" id="add_to_cart">加入购物车</a>',
							'<a href="#" id="add_to_order">立即购买</a>'].join('');
						var placeHtmlStr= ['<a href="#" id="add_to_order">代购买</a>'].join('');
						var myEditHtml=[        
							'<a href="#" id="edit_btn" data-href="/Team/PrimeGoldManagement?ID=',data.ID,'&type=6" style="margin-right:20px;">编辑</a>',
							'<a id="emerald_delete" href="#">删除</a>'].join('');
							if(TEAM==0){//客户端的列表页
								$("#edit_btn_box").html(editHtmlStr);
							}else if(TEAM==2){//现货
								$("#edit_btn_box").html(myEditHtml);
							}else if(TEAM==3){//代下单
								$("#edit_btn_box").html(placeHtmlStr);
							}
							//   @*主题色start*@
			                $(document.createElement("script")).attr("src","/Js/ThemesColor.js").appendTo("html");
							//  @*主题色end*@
							 //放大图片
							var myPhotoBrowserStandalone = myApp.photoBrowser({
							    photos : imgArray,
							    backLinkText: '返回',
							    ofText:"/",
							});
							$$('#look_img').on('click',function () {
								var index=$("#Indicators").find("span.current").index();
								if(APP){
									var ProductImg={};
									 ProductImg['images']=imgArray;
									 ProductImg['index']=index;
									YiYi_APP.showImages(JSON.stringify(ProductImg));
								}else{								
							    	myPhotoBrowserStandalone.open(index);
							   }
							});		
					
					}else{
						myApp.alert(res.result);
					}
					myApp.hideIndicator();//隐藏加载中
				},
				error:function(a,b,c){
					myApp.alert(c);
				}
			});
		},
		//刪除素金
		DelPrimeGolds:function() {
		    myApp.showIndicator();//显示加载中
			 $.ajax({
	            url: "/Team/DeletePrimeGolds",//提交地址
                type: "POST",//提交方式
                data: "{'ID':'" +PrimeGoldsID + "'}",
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var jsonResult = eval('(' + result + ')');//eval()解析单个json对象
	                if (jsonResult && jsonResult.result) {
	                	 myApp.alert('删除成功！', function () {
	                	 	if(APP){
	                	 		YiYi_APP.finish();
	                	 	}else{
	                	 		location.href = "/Team/MyPrimeGold?team=2";
	                	 	}
					    });
	                } else {
	                	myApp.alert(jsonResult.msg);	                   
	                }
	                myApp.hideIndicator();//隐藏加载中
	            }
		        });
		},
		
		
	}
	productItem.init();
}());

//带链接的证书类型
function linkCertType(data) {
	var certLink="-";
	if (data.CertNo){
		if(APP){
			 certLink='<a class="inlays_link" id="app_cert_link">'+data.CertNo+'</a>';
		}else{
			if (data.CertType == "GIA" || data.CertType == "IGI") {
	           certLink='<a class="inlays_link" target="_blank">'+data.CertNo+'</a>';
		    }
		}
       
	 }
	    return certLink;
   
}
//无权限看到价格时的显示
function returnPriceCarat(data){
	//if(data.PriceCarat || data.PriceCarat ==0){
		return '<span>$</span>'+formatUSDPrice((data.PriceCarat)/RATE);
	//}else{
	//	return ('权限不足');
	//}
}
function returnRMBPriceCarat(data){
	//if(data.PriceCarat || data.PriceCarat ==0){
		return '<span>￥</span>'+formatRMBPrice(data.PriceCarat);
	//}else{
	//	return ('权限不足');
	//}
}
function returnPrice(data){
	//if(data.Price || data.Price==0){
		return '<span>$</span>'+formatUSDPrice((data.Price)/RATE);
	//}else{
	//	return '权限不足';
	//}
}
function returnRMBPrice(data){
	//if(data.Price || data.Price==0){
		return '<span>￥</span>'+formatRMBPrice(data.Price);
	//}else{
	//	return ('权限不足');
	//}
}
//app证书链接
function app_linkCert(){
	var data=ItemJson;
	var App_json={};
	App_json.certType=data.CertType;
	App_json.certNumber=data.CertNo;
	App_json.url="http://apitest.checkgems.com:8200/api/v2/certs/"+data.CertType+"/"+data.CertNo;
	App_json.pdfUrl="http://apitest.checkgems.com:8200/api/v2/certs/"+data.CertType+"/"+data.CertNo+".pdf";
	YiYi_APP.showCertificate(JSON.stringify(App_json));
}

//获取类型细分
function GetTextType(type,val,na){
	var valText="";
	if(emerald_type_category[type][na]){
		var len=emerald_type_category[type][na].length;
		for(var i=0;i<len;i++){
			if(val==emerald_type_category[type][na][i][0]){
				valText= (emerald_type_category[type][na][i][1]);
				break;
			}
		}
		if(valText==""){
			valText=val;
		}
		return valText;
	}else{
		return val==""?"-":val;
	}
}

